package com.sxt.system.realm;

import com.sxt.system.common.ActiveUser;
import com.sxt.system.domain.User;
import com.sxt.system.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @ClassName UserRealm
 * @Description TODO
 * @Author 雷哥
 * @Date 2020/3/5 15:13
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做登陆
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到登陆名
        String loginName = authenticationToken.getPrincipal().toString();
        //根据登陆名查询用户
        User user=this.userService.queryUserByLoginName(loginName);
        if(null!=user){
            ActiveUser activeUser=new ActiveUser();
            activeUser.setUser(user);
            //查询角色和权限
            /**
             * 密码匹配
             */
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activeUser
            ,user.getPwd(), ByteSource.Util.bytes(user.getSalt()),this.getName());
            return info;
        }else{
            return null;
        }
    }


    /**
     * 做授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
